<?php

namespace App\System\Base\Services;

use App\Exceptions\Customize\ParamsException;
use App\Exceptions\Customize\TokenException;
use App\System\Cis\Repositories\CisUserPartnerRepository;
use App\System\Cis\Repositories\CisUserRepository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Request;

class TokenService
{
    /**
     * 生成token字符串
     * @return string
     */
    public static function generateToken()
    {
        //获得32位随机字符串
        $str = getRandStr();
        //获得请求的时间戳
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //混入自定义字符串
        $token_salt = config('global.secret_salt');

        return md5($str . $timestamp . $token_salt);
    }

    /**
     * 获取(设置)创客子用户ID
     * @param $user_id 子帐号ID 不传则查询子帐号，传则设置子帐号
     * @return mixed
     */
    public static function getUserId($user_id = 0)
    {
        if(!$user_id)
        {
            $user_id = self::getCacheDataByKey('sunUserId');//创客子用户ID
            if(!$user_id)  throw new TokenException();
        }
        $token = Request::instance()->s;
        $value = self::getCacheDataByKey();//获取session所有信息
        $token_expire = config('global.token_expire');//有效期
        $value['sunUserId'] = $user_id;
        Cache::put($token, $value, $token_expire);
        if (!Cache::has($token)) {
            throw new TokenException([
                'message' => '服务器缓存SessionId失败'
            ]);
        }
        return $user_id;
    }

    /**
     * 根据参数动态获得缓存里的openid、masterUserId、uid、mobile、sunUserId
     * @param $key
     * @return mixed
     * @throws TokenException
     * @throws \Exception
     */
    public static function  getCacheDataByKey($key='')
    {
        $token = Request::instance()->s;
        $value = Cache::get($token);
        if (!$value) return false;
        if (!is_array($value)) $value = json_decode($value, true);
        if (!$key) return $value;
        if (!array_key_exists($key, $value)) return false;
        return $value[$key];
    }

    /**
     * 获取(设置)创客主用户ID
     * @return mixed
     */
    public static function getMasterId()
    {
        //self::generateSession();
        $token = Request::instance()->s;
        $value = self::getCacheDataByKey();//获取session所有信息
        if(!$value) throw new TokenException();
        if(!array_key_exists('uid', $value))
        {
            throw new TokenException();
        }
        if(!array_key_exists('masterUserId', $value))
        {//不存在主用户
            $userAuth = CisUserPartnerRepository::getInstance();
            $user_partner = $userAuth->getDetailByOpenId($value['uid']);
            if($user_partner)
            {
                $masterUserId = $user_partner->user_id;
            }
            else
            {
                if(!array_key_exists('mobile', $value))
                {
                    throw new TokenException();
                }
                $user = CisUserRepository::getInstance();
                $user_info = $user->getMasterUser($value['mobile']);
                if(!$user_info)
                {//没查找到手机匹配的帐号返回0
                    throw new ParamsException([
                        'status'=>'1103',
                        'message' => '对不起，您尚未加入创客系统，请联系客服'
                    ]);
                }
                $userAuth->addData(['type'=>1,'open_id'=>$value['uid'],'user_id'=>$user_info->id]);
                $masterUserId = $user_info->id;
            }
            $value['masterUserId'] = $masterUserId;

            $token_expire = config('global.token_expire');//有效期
            Cache::put($token, $value, $token_expire);
            if (!Cache::has($token)) {
                throw new TokenException([
                    'message' => '服务器缓存SessionId失败'
                ]);
            }
            return $masterUserId;
        }
        else
        {
            return $value['masterUserId'];
        }
    }

    /**
     * 生成session
     */
    public static function generateSession()
    {
        $value = self::getCacheDataByKey();
        if($value)
        {
           return;
        }
        $token = Request::instance()->s;
        $token_expire = config('global.token_expire');//有效期
        Cache::put($token, ['uid'=>'1','mobile'=>'13202068592'], $token_expire);
        if (!Cache::has($token)) {
            throw new TokenException([
                'message' => '服务器缓存SessionId失败'
            ]);
        }
    }

    /**
     * 清除当前子帐号缓存用户ID
     */
    public static function clearSunUserId()
    {
        $token = Request::instance()->s;
        $value = self::getCacheDataByKey();//获取session所有信息
        $token_expire = config('global.token_expire');//有效期
        unset($value['sunUserId']);
        Cache::put($token, $value, $token_expire);
        if (!Cache::has($token)) {
            throw new TokenException([
                'message' => '服务器缓存SessionId失败'
            ]);
        }
        return $value;
    }
}
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    